﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dting_libraries;
using OfficeOpenXml;
using Station_interface;

namespace Alarm_interface
{
    public partial class Alarm_HistoryControl : UserControl
    {
		#region //标题设置
		public string Title_Name
		{
			get { return label1.Text; }
			set { label1.Text = value; }
		}
		public Color Title_FontColor
		{
			get { return label1.ForeColor; }
			set { label1.ForeColor = value; }
		}
		public Color Title_BackColor
		{
			get { return label1.BackColor; }
			set { label1.BackColor = value; }
		}
		public Font Title_Font
		{
			get { return label1.Font; }
			set { label1.Font = value; }
		}

        public mySql_class _mySql_class
        {
            get;
            set;
        }

        #endregion

        public Alarm_HistoryControl()
        {
            InitializeComponent();
			SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
			UpdateStyles();

			dataGridView_init();

		}
		protected override CreateParams CreateParams
		{
			get
			{
				CreateParams cp = base.CreateParams;
				cp.ExStyle |= 0x02000000;
				return cp;
			}
		}

		public void AlarmInfo_Add(string Starttimer, string Endtimer, string Station, string AlarmID, string AlarmInfo, Color? _Color = null)
		{
			for (int i = 0; i < Alarm_HistoryView.Rows.Count; i++)
			{
				if (Alarm_HistoryView.Rows[i].Cells[2].Value.ToString() == AlarmInfo)
				{
					return;
				}
			}

			DataGridViewRowCollection rows = Alarm_HistoryView.Rows;
			object[] values = new string[5] { Starttimer, Endtimer, Station, AlarmID, AlarmInfo };
			rows.Add(values);
			Alarm_HistoryView.Rows[Alarm_HistoryView.Rows.Count - 1].DefaultCellStyle.SelectionForeColor = _Color ?? Color.Red;
			Alarm_HistoryView.Rows[Alarm_HistoryView.Rows.Count - 1].DefaultCellStyle.ForeColor = _Color ?? Color.Red;
		}

		public void dataGridView_init()
		{
			//优化dataGridView控件闪耀现象
			Type dgvType = Alarm_HistoryView.GetType();
			PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
			pi.SetValue(Alarm_HistoryView, true, null);



			//字体大小编辑
			Alarm_HistoryView.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 10.5f, Font.Style | FontStyle.Regular);
			Alarm_HistoryView.DefaultCellStyle.Font = new Font("宋体", 10.5f, Font.Style | FontStyle.Regular);

			//禁止编辑
			Alarm_HistoryView.ReadOnly = true;
			//不显示空白新增行
			Alarm_HistoryView.AllowUserToAddRows = false;
			//添加字段名
			string[] title_str = new string[] { "报警时间", "解除时间", "报警工位", "报警ID", "报警信息" };
			int[] title_width = new int[] { 170, 170, 200, 100, 5000 };//像素距离
															 //增加列头列名称
			Alarm_HistoryView.ColumnCount = title_str.Length;
			Alarm_HistoryView.ColumnHeadersVisible = true;
			DataGridViewCellStyle code = new DataGridViewCellStyle();
			code.BackColor = Color.Beige;
			code.Font = new Font("Verdana", 10, FontStyle.Bold);

			if (title_str.Length > 0)
			{
				for (int i = 0; i < title_str.Length; i++)
				{
					Alarm_HistoryView.Columns[i].Name = title_str[i];
					Alarm_HistoryView.Columns[i].Width = title_width[i];
					//Alarm_dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
					//Alarm_dataGridView.Columns[i].FillWeight = title_width[i];
				}
			}
			//禁止排序
			if (Alarm_HistoryView.Columns.Count > 0)
			{
				for (int i = 0; i < Alarm_HistoryView.Columns.Count; i++)
				{
					Alarm_HistoryView.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
				}
			}
			//禁止用户改变列宽行高
			Alarm_HistoryView.AllowUserToOrderColumns = false;
			Alarm_HistoryView.AllowUserToResizeRows = false;
			Alarm_HistoryView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
			Alarm_HistoryView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;

		}


		//获取报警信息
        private void materialButton1_Click(object sender, EventArgs e)
        {
            string start_date = dateTimePicker1.Value.ToString("yyyy/MM/dd ") + dateTimePicker4.Value.ToString("HH/mm");
            string enf_date = dateTimePicker2.Value.ToString("yyyy/MM/dd ") + dateTimePicker3.Value.ToString("HH/mm");

            if (textBox1.Text==string.Empty)
            {
                date_seek(start_date, enf_date);
            }
            else if (textBox1.Text != string.Empty)
            {
                int index = 0;
                if (int.TryParse(textBox1.Text, out index))
                {
                    string buf = index.ToString("0000");
                    date_seek(buf, start_date, enf_date);

                }
                else
                {
                    MessageBox.Show("输入参数务必为数字，请重新输入", "错误提示");
                }

            }

        }

        //导出excel
        private void MaterialButton2_Click(object sender, EventArgs e)
        {
            export();
        }

        private void TextBox1_MouseDown(object sender, MouseEventArgs e)
        {
            textBox1.Text = string.Empty;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        private void date_seek(string start_date, string end_date)
        {
            try
            {
                var bufMySql = _mySql_class;
                if (bufMySql == null) return;
                DataTable buf_datatable = null;


                buf_datatable = bufMySql.MysqlDate_seek("alarm_data", "start_date", start_date, end_date);
                //显示数据
                GridviewShowDataTable(buf_datatable, Alarm_HistoryView);
            }
            catch (Exception er)
            {
                MessageBox.Show("错误信息：" + er.ToString(), "提示");
            }
        }

        private void date_seek(string column, string start_date, string end_date)
        {
            try
            {
                var bufMySql = _mySql_class;
                if (bufMySql == null) return;
                DataTable buf_datatable = null;

                string[] bufstr = new string[2] { "alarm_id", column };
                buf_datatable = bufMySql.MysqlDate_seek("alarm_data", "start_date", bufstr, start_date, end_date);
                //显示数据
                GridviewShowDataTable(buf_datatable, Alarm_HistoryView);
            }
            catch (Exception er)
            {
                MessageBox.Show("错误信息：" + er.ToString(), "提示");
            }
        }

        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                dataGridView.Rows.Clear();
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        try
                        {
                            dataGridView.Rows.Add();
                            for (int j = 0; j < (table.Columns.Count - 0); j++)
                            {
                                dataGridView.Rows[i].Cells[j].Value = table.Rows[i].ItemArray[j + 1].ToString();

                                //Application.DoEvents();//可以交出控制权但是慢
                            }
                        }
                        catch {; }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        private DataTable DataGridViewTODataTable(DataGridView tableA)
        {
            try
            {
                //DataTable dt = (dataGridView5.DataSource as DataTable);//绑定数据源的情况下

                DataTable dt = new DataTable();

                // 列强制转换
                for (int count = 0; count < tableA.Columns.Count; count++)
                {
                    DataColumn dc = new DataColumn(tableA.Columns[count].Name.ToString());
                    dt.Columns.Add(dc);
                }

                // 循环行
                for (int count = 0; count < tableA.Rows.Count; count++)
                {
                    DataRow dr = dt.NewRow();
                    for (int countsub = 0; countsub < tableA.Columns.Count; countsub++)
                    {
                        dr[countsub] = Convert.ToString(tableA.Rows[count].Cells[countsub].Value);
                    }
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception er)
            {
                return null;
            }
        }

        //导出excel报表
        private void export()
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.FilterIndex = 1;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.Filter = "xlsx文件(*.xlsx)|*.xlsx";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog.FileName.ToString() == string.Empty) return;
                    string localFilePth = saveFileDialog.FileName.ToString();
                    string fileNameExt = localFilePth.Substring(localFilePth.LastIndexOf("\\") + 1);
                    string FilePath = localFilePth.Substring(0, localFilePth.LastIndexOf("\\"));
                    string newFileName = FilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "_" + fileNameExt;


                    DataTable dt = DataGridViewTODataTable(Alarm_HistoryView);
                    if (dt != null && dt.Rows.Count > 0 && dt.Columns.Count > 0)
                    {
                        DataTableTOExcel(dt, newFileName);
                    }
                    else
                    {
                        MessageBox.Show("导出报表失败。", "提示");
                    }

                }

            }
            catch (Exception er)
            {
                MessageBox.Show("导出报表失败，错误信息：" + er.ToString(), "提示");
            }
        }

        //
        private void DataTableTOExcel(DataTable tableA, string path)
        {
            try
            {

                FileInfo file = new FileInfo(path);
                using (ExcelPackage pack = new ExcelPackage(file))
                {
                    ExcelWorksheet w = pack.Workbook.Worksheets["sheet"];
                    if (w != null && w.Name.Equals("sheet")) //判断是否存在该sheet表，存在则删除
                        pack.Workbook.Worksheets.Delete(w);
                    ExcelWorksheet ws = pack.Workbook.Worksheets.Add("sheet");
                    ws.Cells["A1"].LoadFromDataTable(tableA, true); //第二个参数设置为true则显示datable表头
                    pack.Save();
                }


            }
            catch (Exception)
            {

                throw;
            }
        }


    }
}
